<?php
/**
 * @package     Task.php
 * @author      Jing Tang <tangjing3321@gmail.com>
 * @link        http://www.slimphp.net/
 * @version     2.0
 * @copyright   Copyright (c) http://www.slimphp.net
 * @date        2017年7月24日
 */

namespace MaterialLocalization\Models;

use SlimCustom\Libs\Model\Model;
use SlimCustom\Libs\Exception\SlimCustomException;

/**
 * 附件下载任务
 * 
 * @author Jing Tang <tangjing3321@gmail.com>
 */
class Task extends Model
{
    /**
     * 任务表
     * 
     * @var string
     */
    protected $table = 'task';
    
    /**
     * 查询多条任务
     * 
     * {@inheritDoc}
     * @see \SlimCustom\Libs\Model\Model::rows()
     */
    public function rows($pairs = [], $options = [], $fetch_style = null, $cursor_orientation = null, $cursor_offset = null)
    {
        $this->bind(function ($row) {
            if (isset($row['material_info'])) {
                $row['material_info'] = @json_decode($row['material_info'], true);
            }
            return $row;
        });
        return parent::rows($pairs, $options, $fetch_style, $cursor_orientation, $cursor_offset);
    }
    
    /**
     * 创建下载任务
     * 
     * {@inheritDoc}
     * @see \SlimCustom\Libs\Model\Model::create()
     */
    public function create($pairs, $options = [])
    {
        // 内容id必传
        $this->rules([
            'content_id' => 'required|integer',
        ]);
        // 如果存在记录,比较素材
        if ($row = model('task')->where('content_id', '=', $pairs['content_id'])->row(['id, material_info, url'])) {
            $renewPairs = [];
            // 比较附件素材
            $newFilenames = @array_column(json_decode($pairs['material_info'], true), 'filename');
            $localFilenames = @array_column($row['material_info'], 'filename');
            if (is_array($localFilenames) && is_array($newFilenames)) {
                $diff = (count($newFilenames) < count($localFilenames)) ? array_diff($localFilenames, $newFilenames) : array_diff($newFilenames, $localFilenames);
                if ($diff) {
                    $renewPairs['material_info'] = $pairs['material_info'];
                }
            }
            // 比较视频素材
            if ($pairs['url'] && $pairs['url'] != $row['url']) {
                $renewPairs['url'] = $pairs['url'];
            }
            // 素材无变化，抛出异常
            if (! $renewPairs) {
                throw new SlimCustomException(null, 1003);
            }
            // 重新建立下载任务和回调任务
            $renewPairs['status'] = 0;
            $renewPairs['is_notify'] = 0;
            $result = model('Task')->where('content_id', '=', $pairs['content_id'])->renew($renewPairs);
            $insertId = $row['id'];
        }
        // 不存在直接创建下载任务
        else {
            $result = parent::create($pairs, $options);
            $insertId = $result;
        }
        // 创建失败，抛出异常
        if (! $result) {
            throw new SlimCustomException(null, 1002);
        }
        return $insertId;
    }
}